const fs = require('fs')
const nodePath = require('path')

class FileUtils {
  static join(...path) {
    return nodePath.join(...path)
  }

  /**
   *
   * @param startPath
   * @param filter 回调函数，只有一个参数为文件路径，返回true则加入
   * @return {*[]}
   */
  static findSync(startPath, filter = null) {
    let result = [];
    (function finder(path) {
      let files = fs.readdirSync(path);
      files.forEach((val, index) => {
        let fPath = FileUtils.join(path, val);
        let stats = fs.statSync(fPath);
        if (stats.isDirectory()) finder(fPath);
        if (stats.isFile()) {
          if (!filter) {
            result.push(fPath)
          } else {
            if (filter(fPath)) {
              result.push(fPath)
            }
          }
        }
      });
    })(startPath)
    return result;
  }

  static fileToString(path, encoding = 'utf-8') {
    return fs.readFileSync(path, {
      encoding
    })
  }
}

module.exports = FileUtils
